package com.rc.saas.tenant.controller.tenant;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.sms.AliyunSmsUtil;
import com.rc.saas.tenant.common.sms.AliyunSmsTemplateEnum;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 修改邮箱
 * Created by sven on 2019/11/21
 */
@Controller
@RequestMapping("/tenant/user")
public class TenantUserModifyPwdController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(TenantUserModifyPwdController.class);

    private String prefix = "/templates/tenant/user";

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantSmsService tenantSmsService;

    /**
     * 打开修改密码页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/modifyPwd", method = RequestMethod.GET)
    public String modifyPwd(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        model.addAttribute("user", user);
        return prefix + "/modifyPwd";
    }

    /**
     * 获取手机短信验证码
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/genModifyPwdAuthCode", method = RequestMethod.POST)
    @ResponseBody
    public TResponse genModifyPwdAuthCode(HttpSession session) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());

        if (StringUtils.isBlank(findUser.getMobile()) || !findUser.getMobile().matches(HttpConstant.MOBILE_REGEX)) {
            return TResponse.FAIL("手机号格式不正确");
        }
        logger.info("获取手机短信验证码:{},:{}", findUser.getLoginName(), findUser.getMobile());

        //验证码
        String smscode = uidGenerator.genSmsAuthCode();
        Tenant tenant = tenantService.selectByTenantCode(findUser.getTenantCode());
        SendSmsResponse sendResult = AliyunSmsUtil.sendSms(findUser.getMobile(), smscode, AliyunSmsTemplateEnum.CERTIFY, tenant.getSmsSign());

        if (sendResult == null) {
            logger.error("短信系统异常");
            return TResponse.FAIL("短信系统异常");
        }

        if ("OK".equals(sendResult.getCode())) {
            // 更新sms表
            tenantSmsService.updateTenantSmsByTenantCode(tenant.getPhone(), tenant.getTenantCode(), findUser.getTenantUserId(), "0", "tenant,getModifyPwdAuthCode:获取验证码 ,进行注册功能:" + findUser.getMobile(), "获取验证码 ,进行注册功能");
        }else {
            logger.error("短信系统异常:" + sendResult.getMessage());
        }

        //将登录验证码保存到会话中
        String sessionAttr = ShiroConstants.SESSION_TENANT_MODIFYPWD_KEY + findUser.getMobile();
        String sessionAuthCode = smscode + System.currentTimeMillis();
        session.setAttribute(sessionAttr, sessionAuthCode);

        logger.error("获取手机短信验证码 mobile:{},sessionAttr:{},sessionAuthCode:{}", findUser.getMobile(), sessionAttr, sessionAuthCode);

        return TResponse.SUCCESS("验证码已发送");
    }

    /**
     * 保存新密码
     *
     * @param session
     * @param oldPw
     * @param newPw
     * @param authCode
     * @return
     */
    @RequestMapping(value = "/saveNewPw", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse saveNewPw(HttpSession session, String oldPw, String newPw, String authCode) {
        logger.info("controller.saveNewPw request,:{},:{},:{}", oldPw, newPw, authCode);

        TenantUser user = ShiroUtils.getSessionUser();
        TenantUser findUser = tenantUserService.selectByPrimaryKey(user.getTenantUserId());

//        String sessionAttr = ShiroConstants.SESSION_TENANT_MODIFYPWD_KEY + findUser.getMobile();
//        String sessionAuthCode = (String) session.getAttribute(sessionAttr);
//        if (StringUtils.isBlank(sessionAuthCode)) {
//            return TResponse.FAIL("未申请验证码");
//        }
//
//        if (!authCode.equals(sessionAuthCode.substring(0, 6))) {
////            session.removeAttribute(sessionAttr);
//            return TResponse.FAIL("验证码错误");
//        }

        //旧密码对比
        String oldPassword = MD5Utils.encrypt(findUser.getLoginName(), oldPw);
        if (!findUser.getPassword().equals(oldPassword)) {
//            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("旧密码错误");
        }

        try {
            //TenantUser newUser = new TenantUser();
            //newUser.setTenantUserId(findUser.getTenantUserId());
            //newUser.setPassword(MD5Utils.encrypt(findUser.getLoginName(), newPw));
            tenantUserService.updatedUserAndTenantPassword(findUser, newPw);

            //删除验证码
//            session.removeAttribute(sessionAttr);
        } catch (Exception e) {
//            session.removeAttribute(sessionAttr);
            return TResponse.FAIL("操作失败");
        }

        return TResponse.SUCCESS();
    }
}
